import 'package:flutter/material.dart';
import 'package:zpub_att/com/zerogis/zpubatt/constant/AttConstant.dart';
import 'package:zpub_att/com/zerogis/zpubatt/constant/AttFldValueConstant.dart';
import 'package:zpub_att/com/zerogis/zpubatt/widget/AttWidget.dart';
import 'package:zpub_plugin/zpub_plugin.dart';
import 'package:zpub_controls/zpub_controls.dart';
import 'package:zpub_bas/zpub_bas.dart';
import 'package:zpub_svr/zpub_svr.dart';
import 'package:zpub_http/zpub_http.dart';
import 'package:zpub_dbmanager/zpub_dbmanager.dart';
import 'package:zpub_dbmanager/com/zerogis/zpubDbManager/bean/Plugin.dart';

// INSERT INTO plugin(sys, cata, name, titlee, titlec, closeable, uitype, runn, dir, classurl, icon, service, initpara, height, width, modal, autorun, autoobj, prereq, container, button, align) VALUES('21', 'common', 'AttFjPlugin', '属性页', '属性页', 1, 4, 1, 'package:mmdx/com/zerogis/mmdx/scene', 'AttFjPlugin', '', '', '', 0, 0, 0, 0, NULL, NULL, NULL, NULL, 0);

/*
 * 属性页面，并且显示附件：还需要做添加 <br/>
 * 属性相关
 * @param {Object 必传} major 主类型
 * @param {Object 必传} minor 子类型
 * @param {Object 选传} id    查询属性的ID(id和att选其一)
 * @param {Object 选传} att   属性值(id和att选其一)
 * @param {Object 选传} attState 状态(默认是查看[新增_录入=0],[查看=1],[编辑=2])
 * @param {Object 选传} valueChangedMethod 属性修改
 * @param {Object 选传} plugin 插件
 * @param {Object 选传} title  标题名称
 * @param {Object 选传} nullable 附件是否为可空
 * @param {Object 选传} addParam 添加属性的时候添加的参数
 * 附件组件相关(不做参考)
 * @param {Object 必传} major 主类型
 * @param {Object 必传} minor 子类型
 * @param {Object 必传} id    查询属性的ID
 * @param {Object 选传} nullable 是否为可空
 * @param {Object 选传} edit 是否为编辑【true=编辑状态】
 *
 * 需要传入的键：<br/>
 * 传入的值类型： <br/>
 * 传入的值含义：<br/>
 * 是否必传 ：
 */

class AttFjPlugin extends PluginStatefulBase
{
  dynamic mInitParam;

  AttFjPlugin({Key key, @required this.mInitParam, plugin}) : super(key: key, plugin: plugin);

  State<StatefulWidget> createState()
  {
    return new AttFjPluginState();
  }

  static String toStrings()
  {
    return "AttFjPlugin";
  }
}

/*
 * 页面功能 <br/>
 */
class AttFjPluginState<T extends AttFjPlugin> extends PluginBaseState<T>
{
  //附件标识
  final key_doc = GlobalKey();

  void initState()
  {
    super.initState();
    mTitle = EntityManager.getInstance().queryEntityTabNamec(
        widget.mInitParam[DBFldConstant.FLD_MAJOR], widget.mInitParam[DBFldConstant.FLD_MINOR]);
  }

  void initView()
  {
    super.initView();
    if (!CxTextUtil.isEmpty(widget.mInitParam[BasMapKeyConstant.MAP_KEY_VALUE_TITLE]))
    {
      mTitle = widget.mInitParam[BasMapKeyConstant.MAP_KEY_VALUE_TITLE];
    }
  }

  Widget build(BuildContext context)
  {
    Widget body = Stack(children: <Widget>[
      SingleChildScrollView(
        child: Card(child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            createAttWidget(),
            createDupDoc(),
          ],
        ),),
      ),

      Positioned(child: Offstage(
        child: IconButton(iconSize: 50, icon: Image.asset('assets/images/att_commit.png',), onPressed: ()
        {
          doClickOk();
        }),
        offstage: widget.mInitParam[AttConstant.ATT_STATE] == AttFldValueConstant.ATT_STATE_DEFAULT,)
        , bottom: 10, right: 10,)

    ],);
    return buildBody(context, body);
  }


  void onNetWorkSucceed(String method, Object values)
  {
    if (method == 'updateAtt')
    {
      saveDoc();
      showToast(MessageConstant.MSG_UPDATE_SUCCESS);
      finish();
    }
    else if (method == 'addWithId' && values is Map)
    {
      saveDoc();
      showToast(MessageConstant.MSG_DEAL_SUCCESS);
      finish();
    }
    else if (method == 'getSequence' && values is Map)
    {
      dealGetSequence(values);
    }
    else
    {
      super.onNetWorkSucceed(method, values);
    }
  }

  void onClick(Widget view)
  {
    if (view == btn_right)
    {
      runPlugin(0);
    }
  }

  /*
   * 创建属性组件
   */
  Widget createAttWidget()
  {
    Plugin plugin = widget.mInitParam[BasMapKeyConstant.MAP_KEY_PLUGIN] ?? widget.plugin;
    return AttWidget(widget.mInitParam[DBFldConstant.FLD_MAJOR], widget.mInitParam[DBFldConstant.FLD_MINOR],
        mId: widget.mInitParam[DBFldConstant.FLD_ID] ?? DigitValueConstant.APP_DIGIT_VALUE__1,
        mAttVals: widget.mInitParam[BasMapKeyConstant.MAP_KEY_ATT],
        attState: widget.mInitParam[AttConstant.ATT_STATE],
        mValueChangedMethod: widget.mInitParam[BasMapKeyConstant.MAP_KEY_VALUE_CHANGE_METHOD],
        plugin: plugin,
        key: key_btn_border);
  }

  /*
   * 创建附件组件
   */
  Widget createDupDoc()
  {
    // 取附件初始化参数相关
    dynamic att = widget.mInitParam[BasMapKeyConstant.MAP_KEY_ATT];
    Map<String, dynamic> param = {
      DBFldConstant.FLD_MAJOR: widget.mInitParam[DBFldConstant.FLD_MAJOR],
      DBFldConstant.FLD_MINOR: widget.mInitParam[DBFldConstant.FLD_MINOR],
      DBFldConstant.FLD_ID: CxTextUtil.isEmptyObject(att) ? widget.mInitParam[DBFldConstant.FLD_ID] : att[DBFldConstant
          .FLD_ID],
      BasMapKeyConstant.MAP_KEY_NULLABLE: widget.mInitParam[BasMapKeyConstant.MAP_KEY_NULLABLE],
    }; // 初始化参数{major:1,minor:1,id:1}
    int nullable = widget.mInitParam[BasMapKeyConstant.MAP_KEY_NULLABLE]; // 是否为可空
    int attState = widget.mInitParam[AttConstant.ATT_STATE];
    bool edit = attState != null && attState == AttFldValueConstant.ATT_STATE_DEFAULT
        ? false
        : true; // 是否为编辑【true=编辑状态】
    Plugin plugin = widget.mInitParam[BasMapKeyConstant.MAP_KEY_PLUGIN] ?? widget.plugin; // plugin对象

    return DuplicateDocWidget(initPara: param,
        mNullable: nullable,
        mIsEdit: edit,
        plugin: plugin,
        key: key_doc);
  }

  /*
   * 确定按钮
   */
  void doClickOk()
  {
    if (widget.mInitParam[AttConstant.ATT_STATE] == AttFldValueConstant.ATT_STATE_EDIT_ABLE)
    {
      // 编辑
      updateAtt();
    }
    else if (widget.mInitParam[AttConstant.ATT_STATE] == AttFldValueConstant.ATT_STATE_NEW_EDIT)
    {
      // 新增，录入,先查实体表序列号，再填入ID再入库
      querySequence();
    }
  }

  /*
   * 刷新属性
   */
  void updateAtt()
  {
    AttWidgetState state = key_btn_border.currentState;
    Map<String, dynamic> param = state.queryAttKeyMap();
    dynamic att = widget.mInitParam[BasMapKeyConstant.MAP_KEY_ATT];

    param[HttpParamKeyValue.PARAM_KEY_MAJOR] = widget.mInitParam[DBFldConstant.FLD_MAJOR];
    param[HttpParamKeyValue.PARAM_KEY_MINOR] = widget.mInitParam[DBFldConstant.FLD_MINOR];
    param[DBFldConstant.FLD_ID] =
    CxTextUtil.isEmptyObject(att) ? widget.mInitParam[DBFldConstant.FLD_ID] : att[DBFldConstant.FLD_ID];

    SvrAreaSvrService.updateAtt(this, param: param);
  }

  /*
   * 查询实体表序列号
   */
  void querySequence()
  {
    SvrUtilSvrService.getSequence(
        widget.mInitParam[DBFldConstant.FLD_MAJOR], widget.mInitParam[DBFldConstant.FLD_MINOR], this);
  }

  /*
   * 查询实体表序列号
   */
  void addWithID(id)
  {
    AttWidgetState state = key_btn_border.currentState;

    // 准备参数
    Map<String, dynamic> param = state.queryAttKeyMap();
    param[DBFldConstant.FLD_ID] = id;
    dynamic addParam = widget.mInitParam['addParam'];
    if(!CxTextUtil.isEmptyObject(addParam))
    {
      addParam.forEach((key,value)
      {
        param[key] = value;
      });
    }

    SvrAreaSvrService.addWithId(
        widget.mInitParam[DBFldConstant.FLD_MAJOR], widget.mInitParam[DBFldConstant.FLD_MINOR], this, value: param);
  }

  /*
   * 保存附件
   */
  void saveDoc()
  {
    // 准备参数
    dynamic att = widget.mInitParam[BasMapKeyConstant.MAP_KEY_ATT];
    Map<String, dynamic> param = {
      DBFldConstant.FLD_MAJOR: widget.mInitParam[DBFldConstant.FLD_MAJOR],
      DBFldConstant.FLD_MINOR: widget.mInitParam[DBFldConstant.FLD_MINOR],
      DBFldConstant.FLD_MEDIA_ENTITYID: CxTextUtil.isEmptyObject(att)
          ? widget.mInitParam[DBFldConstant.FLD_ID]
          : att[DBFldConstant.FLD_ID]
    };
    DuplicateDocWidgetState state = key_doc.currentState;
    state.saveTempFile(param);
  }

  /*
   * 取实体表序列号
   */
  void dealGetSequence(Map values)
  {
    addWithID(values[DBFldConstant.FLD_ID]);
  }

  @override
  void finish()
  {
    Navigator.pop(context, true);
  }
}

/*
 * 类描述：属性提供的Service
 * 作者：郑朝军 on 2019/6/6
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2019/6/6
 * 修改备注：
 */
class AttFjPluginService extends InterfaceBaseImpl
{
  @override
  Future<T> runPlugin<T extends Object>(State<StatefulWidget> state, {dynamic initPara})
  {
    return StateManager.getInstance().startWidegtState(new AttFjPlugin(mInitParam: initPara), state);
  }

  @override
  Widget runWidget({dynamic initPara})
  {
    return new AttFjPlugin(mInitParam: initPara,);
  }
}
